/*
 * 文件名：HeartBeatReqHandler.java
 * 版权：亚信科技(南京)版权所有
 * 描述：TODO
 * 修改人：xuwei3
 * 修改时间：2015-11-10
 * 修改内容：TODO
 */
package com.ailk.bigdata.etl.realstream.server.protocal.sdtp.netty.handler;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ailk.bigdata.etl.common.server.net.NettyUtil;
import com.ailk.bigdata.etl.realstream.server.model.Header;
import com.ailk.bigdata.etl.realstream.server.model.MessageType;
import com.ailk.bigdata.etl.realstream.server.model.SdtpDataPack;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @description TODO
 * @author [xuwei3]
 * @version [版本号,2015-11-10]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class HeartBeatReqHandler extends SimpleChannelInboundHandler<SdtpDataPack>
{
	private static Logger logger = LoggerFactory.getLogger(HeartBeatReqHandler.class);

	private volatile ScheduledFuture<?> heartBeat;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, SdtpDataPack dataPack) throws Exception
	{
		if (null != dataPack.getHeader() && dataPack.getHeader().getMessageType() == MessageType.linkAuth_Resp.getValue())
		{
			heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS);
		}
		else if (null != dataPack.getHeader() && dataPack.getHeader().getMessageType() == MessageType.linkCheck_Resp.getValue())
		{
			logger.debug("client receive heart beat info to server [" + NettyUtil.getClientAdd(ctx) + "]");
		}
		else
		{
			ctx.fireChannelRead(dataPack);
		}
	}

	/**
	 * 
	 * @description TODO
	 * @author [xuwei3]
	 * @version [版本号,2015-11-10]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	private class HeartBeatTask implements Runnable
	{
		private ChannelHandlerContext ctx;

		public HeartBeatTask(ChannelHandlerContext ctx)
		{
			this.ctx = ctx;
		}

		/**
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run()
		{
			SdtpDataPack sdtpDataPack = builderDataPack();
			logger.debug("client send heart beat info to server [" + NettyUtil.getClientAdd(ctx) + "]");
			ctx.writeAndFlush(sdtpDataPack);
		}

		private SdtpDataPack builderDataPack()
		{
			SdtpDataPack sdtpDataPack = new SdtpDataPack();
			Header header = new Header();
			header.setMessageType(MessageType.linkCheck_Req.getValue());
			sdtpDataPack.setHeader(header);
			return sdtpDataPack;
		}

	}
}
